const Router = require('koa-router')
const router = new Router()
const callCloudDB = require('../utils/callCloudDB.js')
const cloudStorage = require('../utils/callCloudStorage.js')

router.get('/list', async (ctx, next) => {
    const params = ctx.request.query
    const query = `
        db.collection('DingDan').skip(${params.start}).limit(${params.count}).orderBy('createTime','desc').get()
    `
    const res = await callCloudDB(ctx, 'databasequery', query)
    // console.log(res)

    //文件下载链接
    let fileList = []
    const data = res.data
    for (let i = 0, len = data.length; i < len; i++) {
        fileList.push({
            fileid: JSON.parse(data[i]).giftimg,
            max_age: 7200
        })
    }
    const dlRes = await cloudStorage.download(ctx, fileList)
    // console.log(dlRes)
    let returnData = []
    for (let i = 0, len = dlRes.file_list.length; i < len; i++) {
        returnData.push({
            download_url: dlRes.file_list[i].download_url,
            _id: JSON.parse(data[i])._id,
            _openid: JSON.parse(data[i])._openid,
            code: JSON.parse(data[i]).code,
            createTime: JSON.parse(data[i]).createTime,
            giftname: JSON.parse(data[i]).giftname,
            info: JSON.parse(data[i]).info,
            name: JSON.parse(data[i]).name,
            giftimg: JSON.parse(data[i]).giftimg,
            ph: JSON.parse(data[i]).ph,
            region: JSON.parse(data[i]).region,
            state: JSON.parse(data[i]).state,
            username: JSON.parse(data[i]).username
        })
    }
    // console.log(returnData)

    ctx.body = {
        data: returnData,
        code: 20000,
    }
})

router.post('/del', async (ctx, next) => {
    const params = ctx.request.body
    // 删除blog
    const queryBlog = `db.collection('DingDan').doc('${params._id}').remove()`
    const delBlogRes = await callCloudDB(ctx, 'databasedelete', queryBlog)

    ctx.body = {
        code: 20000,
        data: {
            delBlogRes
        }
    }
})

router.get('/getById', async (ctx, next) => {
    const query = `db.collection('DingDan').doc('${ctx.request.query.id}').get()`
    const res = await callCloudDB(ctx, 'databasequery', query)
    ctx.body = {
        code: 20000,
        data: JSON.parse(res.data)
    }
})

router.post('/updatePlaylist', async (ctx, next) => {
    const params = ctx.request.body
    // console.log(params)
    const query = `
        db.collection('DingDan').doc('${params._id}').update({
            data: {
                state: '${params.state}'
            }
        })
    `
    const res = await callCloudDB(ctx, 'databaseupdate', query)
    ctx.body = {
        code: 20000,
        data: res
    }
})

module.exports = router